package com.lxb.myblog.controller.admin;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lxb.myblog.po.Type;
import com.lxb.myblog.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;

@Controller
@RequestMapping("/admin")
public class TypeController {

    @Autowired
    private TypeService typeService;


    @RequestMapping("/types")
    public String types(Model model, @RequestParam(defaultValue = "1", value = "pageNum") Integer pageNum) {
        PageHelper.startPage(pageNum, 10);
        List<Type> types = typeService.getAllType();
        PageInfo<Type> pageInfo = new PageInfo<>(types);
        model.addAttribute("pageInfo", pageInfo);
        return "admin/types";
    }

    @GetMapping("/types/input")
    public String input(Model model) {

        model.addAttribute("type", new Type());

        return "admin/types-input";
    }

    @GetMapping("/types/input/{id}")
    public String editInput(Model model, @PathVariable Integer id) {
        model.addAttribute("type", typeService.getTypeById(id));

        return "admin/types-input";
    }

    @PostMapping("/types/add")
    public String add(Type type, RedirectAttributes attributes) {
        int result;
        if (type.getId() != null) {
            // 更新
            result = typeService.updateType(type);
        } else {
            // 增加
            result = typeService.saveType(type);
        }

        if (result != 1) {
            // 更新或保存失败
            attributes.addFlashAttribute("message", "更新或保存失败");
        } else {
            // 更新或保存成功
            attributes.addFlashAttribute("message", "更新或保存成功");
        }

        return "redirect:/admin/types";
    }

    @GetMapping("/types/delete/{id}")
    public String delete(@PathVariable Integer id) {
        typeService.deleteTypeById(id);

        return "redirect:/admin/types";
    }

}
